package com.hymjweb.demo.framework.util.util;

import com.hymjweb.demo.framework.util.DateUtil;
import org.springframework.util.ClassUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

public class FileUploadUtil {

    /**
     * 上传文件到指定的文件目录,默认位置是static/upload_file
     * @param upLoadFile
     * @return
     */
    public static String uploadFile(MultipartFile upLoadFile){
        String fileName = upLoadFile.getOriginalFilename();
        System.out.println(fileName);
        // 获取扩展名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 获取resources目录路径
        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();

        File parentDir = new File(path + "static/upload_file");

        if (!parentDir.exists()) {
            parentDir.mkdir();
        }

        String name= DateUtil.getSysIdLocal()+ suffixName;

        File destFile = new File(parentDir, name);

        try {
            // 上传的文件写入到目标文件中
            upLoadFile.transferTo(destFile);
            return name;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    public static void downLoadFile(HttpServletRequest request, HttpServletResponse response,File file){
        String fileName=request.getParameter("fileName");
        if(fileName!=null){
            if(file.exists()){
                // 配置文件下载
                response.setHeader("content-type", "application/octet-stream");
                response.setContentType("application/octet-stream");
                // 下载文件能正常显示中文
                response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

                // 实现文件下载
                byte[] buffer = new byte[1024];
                int len=0;
                BufferedInputStream bis = null;
                try{
                    bis=new BufferedInputStream(new FileInputStream(file));
                    OutputStream os=response.getOutputStream();

                    while((len=bis.read(buffer))>0){
                        os.write(buffer,0,len);
                    }
                    os.flush();
                    os.close();
                }
                catch (Exception e){
                    e.printStackTrace();
                }
                finally {
                    if(bis!=null){
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }


            } // end if file.exists
        } // end if fileName
    }

}
